<template>
  <div class="min-h-screen from-slate-900 to-slate-800 flex items-center justify-center p-4">
    <!-- 登录卡片 -->
    <div
      class="w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden transform transition-all duration-500 hover:shadow-blue-500/20">
      <!-- 顶部装饰条 -->
      <div class="h-1.5 bg-gradient-to-r from-blue-600 to-blue-400"></div>

      <!-- 登录内容 -->
      <div class="p-8">
        <!-- 系统名称 -->
        <div class="text-center mb-10">
          <h1 class="text-[clamp(1.5rem,3vw,2rem)] font-bold text-slate-800 mb-2 tracking-tight">
            冲压加工管理系统
          </h1>

        </div>

        <!-- 登录表单 -->
        <div class="space-y-6">
          <!-- 用户名输入 -->
          <div class="space-y-2" v-if="isRegister">
            <label for="name" class="block text-sm font-medium text-slate-700">姓名</label>
            <div class="relative">
              <input type="text" id="name" v-model="name" required
                class="w-full pl-10 pr-4 py-3 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 outline-none"
                placeholder="请输入姓名">
            </div>
          </div>
          <!-- 用户名输入 -->
          <div class="space-y-2">
            <label for="username" class="block text-sm font-medium text-slate-700">用户名</label>
            <div class="relative">
              <input type="text" id="username" v-model="username" required
                class="w-full pl-10 pr-4 py-3 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 outline-none"
                placeholder="请输入用户名">
            </div>
          </div>

          <!-- 密码输入 -->
          <div class="space-y-2">
            <label for="password" class="block text-sm font-medium text-slate-700">密码</label>
            <div class="relative">

              <input :type="showPassword ? 'text' : 'password'" id="password" v-model="password" required
                class="w-full pl-10 pr-10 py-3 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 outline-none"
                placeholder="请输入密码">
            </div>
          </div>
          <!-- 角色选择 -->
          <div v-if="isRegister" class="space-y-2">
            <label for="role" class="block text-sm font-medium text-slate-700">角色</label>
            <div class="relative">

              <select id="role" v-model="selectedRole" required
                class="w-full pl-10 pr-4 py-3 rounded-lg border border-slate-300 focus:ring-2 focus:ring-blue-500 focus:border-blue-500 transition-all duration-200 outline-none">
                <option v-for="role in roles" :key="role.value" :value="role.value">
                  {{ role.label }}
                </option>
              </select>
            </div>
          </div>
          <div class="text-right" v-if="!isRegister">
            <a @click="openRegister" class="text-[#165dff] cursor-pointer">注册</a>
          </div>
          <div class="text-right" v-if="isRegister">
            <a @click="openRegister" class="text-[#165dff] cursor-pointer">登录</a>
          </div>

          <!-- 登录按钮 -->
          <button @click="handleLogin" v-if="!isRegister"
            class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition-all duration-200 transform hover:scale-[1.02] active:scale-[0.98] disabled:opacity-70 disabled:cursor-not-allowed flex items-center justify-center gap-2"
            tabindex="0">
            <span>登录</span>
          </button>
          <button @click="handleLogin" v-if="isRegister"
            class="w-full bg-blue-600 hover:bg-blue-700 text-white font-medium py-3 px-4 rounded-lg transition-all duration-200 transform hover:scale-[1.02] active:scale-[0.98] disabled:opacity-70 disabled:cursor-not-allowed flex items-center justify-center gap-2">
            <span>注册</span>
          </button>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import JSONbig from 'json-bigint'
import Message from "../components/Message/Message.js";
// 表单数据
const name = ref('');
const username = ref('');
const password = ref('');
const selectedRole = ref(1);
const showPassword = ref(false);
// 路由实例
const router = useRouter();
const isRegister = ref(false)
const roles = ref([
  { label: '管理员', value: 0 },
  { label: '生产管理员', value: 1 },
  { label: '物料工', value: 2 },
  { label: '操作员', value: 3 }
]);
const openRegister = () => {
  isRegister.value = !isRegister.value
}
// 登录处理
const handleLogin = async () => {
  const info = JSONbig.parse(localStorage.getItem('CYGL'))
  if (isRegister.value) {
    axios.post('/api/user/register?userIdStr=' + info.userId, {
      name: name.value,
      username: username.value,
      password: password.value,
      role: selectedRole.value
    }).then(res => {
      if (res.data.Code == "200") {
        Message.success('提交注册，等待审核')
        name.value = ''
        username.value = ''
        password.value = ''
      } else {
        Message.error(res.data.Msg)
      }
    })
  } else {
    axios.get('/api/user/login?username=' + username.value + "&password=" + password.value + "&userIdStr=" + info.userId).then(res => {
      if (res.data.Code == "200") {
        localStorage.setItem('token', res.data.Data);
        // router.push('/');
        axios.get('/api/user/role').then(roleRes => {
          if (roleRes.data.Code === "200") {
            const userRole = roleRes.data.Data;
            localStorage.setItem('role', userRole); // 保存角色到本地

            // 根据角色跳转不同页面
            let redirectPath = '/'; // 默认路径
            switch (userRole) {
              case 0: // 管理员
                redirectPath = '/user'; // 管理员默认到用户管理
                break;
              case 1: // 生产管理员
                redirectPath = '/process'; // 生产管理员默认到工艺管理
                break;
              case 2: // 物料工
                redirectPath = '/identify/device'; // 物料工默认到仓库管理
                break;
              case 3: // 操作员
                redirectPath = '/task'; // 操作员默认到任务管理
                break;
              default:
                redirectPath = '/';
            }
            router.push(redirectPath);
          }
        });
      } else {
        Message.error(res.data.Msg)
      }
    })
  }
};


onMounted(() => {
  const param = new URLSearchParams(window.location.search);
  var url = param.get('user_api')
  var token = param.get('token')
  var clientid = param.get('clientid')
  if (url != null && token != null && clientid != null) {
    axios.get(url, {
      headers: {
        'Authorization': "Bearer " + token,
        'clientid': clientid
      }
    }).then(res => {
      var userId = res.data.data.userId
      axios.get('/api/user/isadmin?userId=' + userId).then(res1 => {
        if (res1.data.Code == "200") {
          router.push('/');
          localStorage.setItem('token', res1.data.Data);
          localStorage.setItem('CYGL', JSON.stringify(res.data.data));
          localStorage.setItem('role', res1.data.Data.Data);

        }
      })
    })
  }


});
</script>

<style scoped>
/* 动画效果增强 */
input:focus {
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* 输入框动画 */
input {
  transition: all 0.2s ease;
}

input:focus-within {
  border-color: #3b82f6;
}

/* 按钮状态动画 */
button {
  transition: all 0.2s ease;
}
</style>